import 'dart:convert';
import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_handle_cache.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_open_custom_media.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_preview_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_record_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_upload_video.dart';
import 'package:dk_flutter_module_sale/common/plugin/bean/bean_user_info.dart';
import 'package:dk_flutter_module_sale/common/plugin/plugin_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/route/sale_check_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/Image/image_url.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_check_api.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/image_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/password_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/request_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/bean/upload_room_paint_bean.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/logic/room_paint_logic.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/image_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/password_tip_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/section_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/single_button_widget.dart';
import 'package:dk_flutter_module_sale/sale/sale_check/room_paint/widget/toast_widget.dart';

@ARoute(url: SaleCheckWidgetRoute.SALE_CHECK_ROOM_PAINT_ADD)
//房态采集
class PageRoomPaintAdd extends CommonPageWithTrack {
  final BoostRouteOption option;

  PageRoomPaintAdd(this.option) : super();
  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("巡房-房态采集-添加", null);
  }
  @override
  void onInitState(CommonPageBloc pageBloc, {Map<String, Bloc> extraBlocMap}) async{
    RequestBean requestBean = RequestBean.fromJson(this.option.params);
    //读取缓存
    CommonPlugin commonPlugin = CommonPlugin();
    String key = await RoomPaintAddConst.saveKey(requestBean.suiteId);
    CacheOption cacheOption = CacheOption.get(key: key);
    commonPlugin.handleCache(option: cacheOption,handleResult: (HandleCacheResultBean bean){
      Map cacheMap;
      if(objNotEmpty(bean) && stringNotEmpty(bean.getResult)) {
        const JsonCodec json = JsonCodec();
        cacheMap = json.decode(bean.getResult);
      }
      //请求数据
      pageBloc.pageHttpGet(
        showFailMsg: true,
          path: SaleCheckApi.roomPaintInfo,
          queryMap: {"suiteId": requestBean.suiteId},
          widgetBuilderByData: (dynamic data) {
            AreaDataBean dataBean = AreaDataBean.fromJson(data);
            if(objNotEmpty(cacheMap)){
              for (int i = 0; i < dataBean.areas.length; i++) {
                AreaBean areaBean = dataBean.areas[i];
                if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeOut  && objNotEmpty(cacheMap[RoomPaintAddConst.roomOutKey])) {
                  areaBean.recordVideoResultBean = RecordVideoResultBean.fromJson(cacheMap[RoomPaintAddConst.roomOutKey]);
                } else if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeCommon && objNotEmpty(cacheMap[RoomPaintAddConst.roomCommonKey])) {
                  areaBean.recordVideoResultBean = RecordVideoResultBean.fromJson(cacheMap[RoomPaintAddConst.roomCommonKey]);
                } else if(objNotEmpty(cacheMap[areaBean.roomCode])){
                  areaBean.recordVideoResultBean = RecordVideoResultBean.fromJson(cacheMap[areaBean.roomCode]);
                }
              }
            }
            return RoomPaintStatefulWidget(
                pageBloc,
                requestBean,
                dataBean,
                key
            );
          });
    });
  }
}

class RoomPaintStatefulWidget extends StatefulWidget {
  final CommonPageBloc pageBloc;
  final RequestBean paramBean;
  final AreaDataBean dataBean;
  final String saveKey;
  RoomPaintStatefulWidget(
    this.pageBloc,
      this.paramBean,
      this.dataBean,
      this.saveKey
  );

  @override
  _RoomPaintStatefulWidgetState createState() =>
      _RoomPaintStatefulWidgetState(pageBloc,this.paramBean,this.dataBean,this.saveKey);
}

class RoomPaintAddConst {
  static const String roomPaintPrefix = "RoomPaintPrefix";
  static const String roomOutKey = "roomOut";
  static const String roomCommonKey = "roomCommon";
  static Future<String> saveKey(String suiteId) async{
    UserInfoBean info = await CommonPlugin().getUserInfo();
    String id = generateMd5(info.id);
    return "$roomPaintPrefix + $suiteId + ${id}";
  }
}

class _RoomPaintStatefulWidgetState extends State<RoomPaintStatefulWidget> {
  Map cacheMap;
  final CommonPageBloc pageBloc;
  DkCenterDialog tipDialog;
  AreaDataBean dataBean;
  final RequestBean paramBean;
  final String saveKey;
  bool intoDetailPage = false;
  bool isUpLoading = false;
  CommonPlugin commonPlugin = CommonPlugin();
  _RoomPaintStatefulWidgetState(
    this.pageBloc,
      this.paramBean,
      this.dataBean,
      this.saveKey
  );
  void refresh(){
    //请求数据
    pageBloc.dataHttpGet(
        showFailMsg: true,
        path: SaleCheckApi.roomPaintInfo,
        queryMap: {"suiteId": paramBean.suiteId},
        handleResult: (dynamic data) {
          setState(() {
            this.dataBean = AreaDataBean.fromJson(data);
          });
        });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    FlutterBoost.singleton.addBoostContainerLifeCycleObserver((
        ContainerLifeCycle state, BoostContainerSettings settings) {
      if(settings.name != SaleCheckWidgetRoute.SALE_CHECK_ROOM_PAINT_ADD) {
        return;
      }
      if(state == ContainerLifeCycle.Appear) {
        if(intoDetailPage){
          this.refresh();
        }

      } else if(state == ContainerLifeCycle.Destroy) {
        FlutterBoost.singleton.observersHolder.removeObserver(this);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DkAppBar(
          DKAppBarParams.withBackMenu(context, [], title: Text("房态采集"))),
      backgroundColor: Colors.white,
      body: SafeArea(
        bottom: true,
        child: Stack(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(bottom: 60),
              color: Colors.white,
              child: CustomScrollView(
                physics: ScrollPhysics(),
                slivers: getSliverToBoxAdapters(),
              ),
            ),
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: this.getBottomWidget(),
            )
          ],
        ),
      ),
    );
  }

  void cancelLoading(LoadingDialog loadingDialog){
    loadingDialog.cancel();
    isUpLoading = false;
  }


  Widget getBottomWidget() {
    return SingleButtonWidget(
      title: "完成",
      tapAction: this.finishAction,
    );
  }

  List<Widget> getSliverToBoxAdapters() {
    List<Widget> boxAdapters = List<Widget>();
    if (this.dataBean == null) return boxAdapters;
    Widget gap = SliverToBoxAdapter(
        child: Container(
      color: Color(0xFFF7F8FA),
      height: 10,
    ));
    //外部和公共视频
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeOut) {
        boxAdapters.add(SliverToBoxAdapter(
            child: SectionWidget(
          title: areaBean.areaName,
          bottomLineHidden: false,
        )));
        boxAdapters.addAll(videoArea(areaBean));
        boxAdapters.add(gap);
      } else if (areaBean.enType ==
          RoomEnvironmentType.RoomEnvironmentTypeCommon) {
        boxAdapters.add(SliverToBoxAdapter(
            child: SectionWidget(
          canAdd: areaBean.flag,
          title: areaBean.areaName,
          getPasswordText: areaBean.flag ? "获取外门密码" : "",
          tapAction: () {
            getPassWord(areaBean);
          },
          bottomLineHidden: false,
        )));
        boxAdapters.addAll(videoArea(areaBean));
        boxAdapters.add(gap);
      }
    }
    SliverToBoxAdapter separateLine = SliverToBoxAdapter(
      child: Divider(
        height: 0.5,
        indent: 15,
        endIndent: 15,
        color: Color(0xFFEBEBEB),
      ),
    );

    ///房间内部视频
    bool addInnerHeader = false;
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner) {
        if (addInnerHeader == false) {
          boxAdapters.add(SliverToBoxAdapter(
              child: SectionWidget(
            title: "房间内部视频",
            bottomLineHidden: false,
          )));
          addInnerHeader = true;
        }
        boxAdapters.add(SliverToBoxAdapter(
            child: SectionWidget(
                titleStyle: TextStyle(
                    color: Color(0xFF666666),
                    fontSize: 14,
                  fontWeight: FontWeight.w600
                ),
                canAdd: areaBean.flag,
                title: areaBean.areaName,
                getPasswordText: areaBean.flag ? "获取内门密码" : "",
                tapAction: () {
                  getPassWord(areaBean);
                })));
        boxAdapters.addAll(videoArea(areaBean));
        if (i != this.dataBean.areas.length - 1) {
          boxAdapters.add(separateLine);
        }
      }
    }
    return boxAdapters;
  }

  void getPassWord(AreaBean areaBean) {
    Map<String,dynamic> map = Map();
    if(areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeCommon) {
      map["suiteId"] = this.paramBean.suiteId;
    } else if(areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner){
      map["suiteId"] = this.paramBean.suiteId;
      map["roomCode"] = areaBean.roomCode;
    }
    this.pageBloc.dataHttpGet(
      showFailMsg: true,
        handleErrorCode: (DefaultResponseData data){
          toast("${data.msg}");//非0000
        },
        path:SaleCheckApi.roomPaintGetPassword,
        queryMap: map,
        handleResult: (dynamic data) {
          PassWordBean bean = PassWordBean.fromJson(data);
          String suffixStr = "  " + bean.suiteAdrr;
          if(areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner) {
            showPasswordTipDialog(
                areaBean.roomCode + suffixStr, RoomPaintLogic.doorTypeStr(areaBean, bean));
          } else {
            showPasswordTipDialog(bean.suiteId + suffixStr, RoomPaintLogic.doorTypeStr(areaBean, bean));
          }
        });
  }

  List<Widget> videoArea(AreaBean areaBean) {
    List<Widget> boxAdapters = List<Widget>();
    int count = 0;
    if (areaBean.flag) {
      count = 1;
    }
    count += areaBean.url.length;
    EdgeInsets padding;;
    if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeInner) {
      padding = EdgeInsets.only(left: 10, right: 10, top: 0, bottom: 0);
    } else {
      padding = EdgeInsets.only(left: 10, right: 10, top: 17, bottom: 17);
    }
    SliverPadding sliverPadding = SliverPadding(
      padding: padding,
      sliver: new SliverGrid(
        //Grid
        gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 4,
          mainAxisSpacing: 0,
          crossAxisSpacing: 0.0,
          childAspectRatio: 1.0,
        ),
        delegate: new SliverChildBuilderDelegate(
          (BuildContext context, int index) {
            bool lookOnly = true;
            String imageUrl;
            if (objNotEmpty(areaBean.recordVideoResultBean) &&
                index == count - 1) {
              lookOnly = false;
              imageUrl = areaBean.recordVideoResultBean.videoFrameImgPath;
            } else {
              if (areaBean.flag && index == count - 1) {
                imageUrl = AppNetWorkImage.cameraIcon;
              } else {
                Url uri = areaBean.url[index];
                imageUrl = uri.imageUrl;
              }
            }
            return ImageWidget(
              deleteAction: () {
                setState(() {
                  RoomPaintLogic.deleteNativeVideo([areaBean.recordVideoResultBean]);
                  areaBean.recordVideoResultBean = null;
                });
              },
              tapAction: () {
                RoomPaintLogic.paintVideoTapAction(context,areaBean, index, count,this);
              },
              imageURL: imageUrl,
              lookOnly: lookOnly,
            );
          },
          childCount: count,
        ),
      ),
    );
    boxAdapters.add(sliverPadding);
    return boxAdapters;
  }

  void toast(String msg) {
    showWidgetToast(ToastWidget(
      title: msg,
    ));
  }

  bool checkForgetVideoPass(){
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.flag && objEmpty(areaBean.recordVideoResultBean)) {
        toast("您未上传" + areaBean.areaName + "请上传后在进行提交!");
        return false;
      }
    }
    return true;
  }


  void finishAction() {
    //检查应该上传的视频
    if(checkForgetVideoPass() == false){
      return;
    }
    //上传视频
    UploadVideoBean uploadVideoBean =
        new UploadVideoBean(picUploadConfig: UploadConfigBean.publicSaleOut());
    List<RecordVideoResultBean> videoList = List();
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if(objNotEmpty(areaBean.recordVideoResultBean)) {
        videoList.add(areaBean.recordVideoResultBean);
      }
    }
    if(videoList.length == 0){
      toast("您没有需要上传的视频!");
      return;
    }
    uploadVideoBean.videoList = videoList;
    if(isUpLoading) {
      toast("视频正在上传，请稍后。。。");
      return;
    } else {
      isUpLoading = true;
    }
    LoadingDialog loadingDialog = LoadingDialog.create().show(context);
    this.commonPlugin.uploadVideo(
        bean: uploadVideoBean,
        handleResult: (UploadVideoResultBean uploadVideoResultBean) {
          if (uploadVideoResultBean.failList.length > 0) {
            cancelLoading(loadingDialog);
            toast("视频上传出错,请重新上传!");
            return;
          }
          Map param = RoomPaintLogic.createUploadData(uploadVideoResultBean,videoList,dataBean,this.paramBean.suiteId);
          this.pageBloc.dataHttpPost(
              path: SaleCheckApi.roomPaintSave,
              data:param ,
              showFailMsg: true,
              handleResult: (dynamic data){
                cancelLoading(loadingDialog);
                toast("视频上传成功");
                intoDetailPage = true;
                RouteUtil.goPage(SaleCheckWidgetRoute.SALE_CHECK_ROOM_PAINT_DETAIL + "?suiteId=${this.paramBean.suiteId}");
                RoomPaintLogic.deleteNativeVideo(videoList);
                deleteUnUploadVideoCache();
              },
              handleErrorCode: (DefaultResponseData data){
                cancelLoading(loadingDialog);
                toast("${data.msg}");//非0000
              },
            handleFailResult: (dynamic data1,dynamic data2){
              cancelLoading(loadingDialog);
            }
          );
        });
  }

  Map createUploadData(UploadVideoResultBean uploadVideoResultBean,List<RecordVideoResultBean>sourceList) {
    //匹配房间和对应的视频和图片
    UploadRoomPaintBean saveUploadRoomPaintBean = UploadRoomPaintBean();
    saveUploadRoomPaintBean.suiteId = this.paramBean.suiteId;
    List<Videos> successList =  uploadVideoResultBean.successList.map((UploadVideoSuccessBean resultItem){
      Videos videos = Videos();
      videos.imageKey = resultItem.imageCode;
      videos.videoKey = resultItem.videoCode;
      for(int i = 0;i < sourceList.length;i++) {
        for(int j = 0;j < this.dataBean.areas.length;j++){
          AreaBean areaBean = this.dataBean.areas[j];
          if(areaBean.recordVideoResultBean.videoFilePath == resultItem.videoPath) {
            videos.areaType = areaBean.areaType;
            videos.timeConsuming = int.parse(areaBean.recordVideoResultBean.videoFileTime);
            videos.size = int.parse(areaBean.recordVideoResultBean.videoFileSize);
            videos.roomCode = areaBean.roomCode;
            break;
          }
        }
      }
      return videos;
    }).toList();
    saveUploadRoomPaintBean.videos = successList;
    Map map = saveUploadRoomPaintBean.toJson();
    return map;
  }

  void showPasswordTipDialog(String firstName, String secondName) {
    DkCenterDialog pwdTips = DkCenterDialog.create(
      CenterDialogOption(
        (BuildContext context) {
          return PasswordStatelessWidget(
            firstName: firstName,
            secondName: secondName,
            tipName: "我知道了",
            tapAction: () {
            },
          );
        },
        handleResult: (bool isConfirm) {
        },
      ),
    );
    pwdTips.show(context);
  }

  ///保存未上传视频
  void saveUnUploadVideo(){
    Map<String,dynamic> roomMap = new Map();
    for (int i = 0; i < this.dataBean.areas.length; i++) {
      AreaBean areaBean = this.dataBean.areas[i];
      if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeOut) {
        if(objNotEmpty(areaBean.recordVideoResultBean)) {
          roomMap[RoomPaintAddConst.roomOutKey] = areaBean.recordVideoResultBean.toJson();
        }
      } else if (areaBean.enType == RoomEnvironmentType.RoomEnvironmentTypeCommon) {
        if(objNotEmpty(areaBean.recordVideoResultBean)) {
          roomMap[RoomPaintAddConst.roomCommonKey] = areaBean.recordVideoResultBean.toJson();
        }
      } else {
        if(objNotEmpty(areaBean.recordVideoResultBean)) {
          roomMap[areaBean.roomCode] = areaBean.recordVideoResultBean.toJson();
        }
      }
    }
    if(roomMap.keys.length > 0) {
      CacheOption cacheOption = CacheOption.asyncPut(key: saveKey, value: roomMap);
      this.commonPlugin.handleCache(option: cacheOption);
    } else {
      CacheOption cacheOption = CacheOption.asyncRemove(key: saveKey);
      this.commonPlugin.handleCache(option: cacheOption);
    }
  }
  ///删除未上传视频的缓存
  void deleteUnUploadVideoCache(){
    CacheOption cacheOption = CacheOption.asyncRemove(key: RoomPaintAddConst.roomPaintPrefix + this.paramBean.suiteId);
    this.commonPlugin.handleCache(option: cacheOption);
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    ///保存视频
    saveUnUploadVideo();
  }
}

